package com.shipment.controller.admin;

import com.shipment.common.Result;
import com.shipment.model.delivery.DeliveryOrderDTO;
import com.shipment.model.delivery.DeliveryOrderQuery;
import com.shipment.service.DeliveryOrderService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

/**
 * 管理员发货订单控制器
 */
@Tag(name = "管理员-发货订单管理接口")
@RestController
@RequestMapping("/api/admin/delivery/order")
@RequiredArgsConstructor
public class AdminDeliveryOrderController {

    private final DeliveryOrderService deliveryOrderService;

    /**
     * 管理员审核订单状态（通过/驳回）
     */
    @Operation(summary = "审核订单状态")
    @PutMapping("/audit/{id}/{status}")
    public Result auditOrderStatus(
            @Parameter(description = "发货订单ID") @PathVariable Long id,
            @Parameter(description = "订单状态: 0=待审核，1=已审核") @PathVariable Integer status) {
        // 确保状态是有效的
        if (status != 0 && status != 1) {
            return Result.error("状态参数错误，只允许 0=待审核，1=已审核");
        }
        return deliveryOrderService.updateOrderStatus(id, status);
    }

    /**
     * 管理员分页查询发货订单（可按状态筛选）
     */
    @Operation(summary = "管理员分页查询发货订单")
    @PostMapping("/page")
    public Result pageDeliveryOrders(@RequestBody DeliveryOrderQuery query) {
        return Result.success(deliveryOrderService.pageDeliveryOrders(query));
    }

    /**
     * 管理员获取发货订单详情
     */
    @Operation(summary = "管理员获取发货订单详情")
    @GetMapping("/detail/{id}")
    public Result getDeliveryOrderById(@Parameter(description = "发货订单ID") @PathVariable Long id) {
        return deliveryOrderService.getDeliveryOrderById(id);
    }

    /**
     * 管理员更新发货订单
     */
    @Operation(summary = "管理员更新发货订单")
    @PutMapping("/update")
    public Result updateDeliveryOrder(@RequestBody DeliveryOrderDTO orderDTO) {
        return deliveryOrderService.updateDeliveryOrder(orderDTO);
    }


    /**
     * 创建发货订单
     */
    @Operation(summary = "创建发货订单")
    @PostMapping("/create")
    public Result createDeliveryOrder(@RequestBody DeliveryOrderDTO orderDTO) {
        return deliveryOrderService.createDeliveryOrder(orderDTO);
    }


    /**
     * 管理员删除发货订单（无论什么状态都可以删除）
     */
    @Operation(summary = "管理员删除发货订单")
    @DeleteMapping("/delete/{id}")
    public Result adminDeleteDeliveryOrder(@Parameter(description = "发货订单ID") @PathVariable Long id) {
        // 管理员直接强制删除，不检查订单状态
        if (id == null) {
            return Result.error("参数错误");
        }
        // 通过baseMapper直接删除，不走service层的状态检查
        boolean success = deliveryOrderService.removeById(id);
        if (success) {
            return Result.success("删除发货订单成功");
        } else {
            return Result.error("删除发货订单失败");
        }
    }
}
